package com.vancouver.knows.ui.activity;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.webkit.GeolocationPermissions;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.TextView;

import butterknife.Bind;
import butterknife.ButterKnife;

import com.github.ppamorim.dragger.DraggerActivity;
import com.github.ppamorim.dragger.DraggerPosition;
import com.pangu.util.StringUtil;
import com.vancouver.knows.R;
import com.vancouver.knows.ui.base.BaseActivity;
import com.vancouver.knows.util.AppUtils;

import java.lang.ref.WeakReference;

/**
 * WebView页面
 *
 * @author cxlin
 */
public class WebViewActivity extends DraggerActivity {

    public static final String DRAG_POSITION_EXTRA = "drag_position_extra";

    @Bind(R.id.webview)
    public WebView webView;
    @Bind(R.id.toolbar)
    public Toolbar toolbar;
    @Bind(R.id.toobarTitle)
    public TextView toobarTitle;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        overridePendingTransition(0, 0);
        super.onCreate(savedInstanceState);
        setShadowView(R.layout.activity_shadow);
        setContentView(R.layout.activity_webview);
        ButterKnife.bind(this);

        Intent intent = getIntent();
        if (intent == null) {
            return;
        }

        String url = intent.getStringExtra("url");
        final String html = intent.getStringExtra("html");
        if (StringUtil.isEmptyString(url) && StringUtil.isEmptyString(html)) {
            return;
        }

        setTension(100);
        setFriction(30);
        setSlideEnabled(false);
        DraggerPosition draggerPosition = (DraggerPosition) intent.getSerializableExtra(DRAG_POSITION_EXTRA);
        if (draggerPosition == null) {
            setDraggerPosition(DraggerPosition.TOP);
        } else {
            setDraggerPosition(draggerPosition);
        }

        String title = intent.getStringExtra("title");
        toolbar.setTitle("");
        setSupportActionBar(toolbar);
        toolbar.setNavigationIcon(getResources().getDrawable(R.drawable.back));
        toobarTitle.setText(StringUtil.isEmptyString(title)?"":title);

        webView.getSettings().setGeolocationDatabasePath(getFilesDir().getPath());
        webView.getSettings().setGeolocationEnabled(true);
        webView.getSettings().setJavaScriptEnabled(true);
        webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
        webView.getSettings().setSupportMultipleWindows(true);
        webView.getSettings().setBuiltInZoomControls(true);
        webView.getSettings().setPluginState(WebSettings.PluginState.ON);
        webView.setWebViewClient(new WebViewClient(){
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                if(!StringUtil.isEmptyString(html)){
                    return true;
                }
                return super.shouldOverrideUrlLoading(view, url);
            }
        });
        webView.setWebChromeClient(new RichWebChromeClient(this));
        if(!StringUtil.isEmptyString(url)){
            webView.loadUrl(url);
        }else{
            webView.loadDataWithBaseURL(null, html, "text/html", "utf-8", null);
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            onBackPressed();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    private static class RichWebChromeClient extends WebChromeClient {
        private final WeakReference<Activity> mainActivityWeakRef;

        public RichWebChromeClient(Activity activity) {
            this.mainActivityWeakRef = new WeakReference<Activity>(activity);;
        }

        @Override
        public void onGeolocationPermissionsHidePrompt() {
            super.onGeolocationPermissionsHidePrompt();
        }

        @Override
        public void onGeolocationPermissionsShowPrompt(final String origin,
                                                       final GeolocationPermissions.Callback callback) {
            if (mainActivityWeakRef.get() != null && !mainActivityWeakRef.get().isFinishing()) {
                AlertDialog.Builder builder = new AlertDialog.Builder(mainActivityWeakRef.get());
                builder.setMessage(R.string.position_request_dis);
                OnClickListener dialogButtonOnClickListener = new OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int clickedButton) {
                        if (DialogInterface.BUTTON_POSITIVE == clickedButton) {
                            callback.invoke(origin, true, true);
                        } else if (DialogInterface.BUTTON_NEGATIVE == clickedButton) {
                            callback.invoke(origin, false, false);
                        }
                    }
                };
                builder.setPositiveButton(R.string.allow, dialogButtonOnClickListener);
                builder.setNegativeButton(R.string.deny, dialogButtonOnClickListener);
                builder.show();
                super.onGeolocationPermissionsShowPrompt(origin, callback);
            }
        }
    }
}
